﻿/// <reference path="RemoteKmDb.js"/>
/// <reference path="BrowserKmDb.js"/>
/// <reference path="LoadLocal.js"/>
/// <reference path="jquery-1.5-vsdoc.js"/>
/// <reference path="jquery.json.js"/>
/// <reference path="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"/>
/// <reference path="Helper.js"/>
/// <reference path="Params.js"/>

function syncFromRemoteKilometers() {
//    var datum = new Date(Date());
//    var m = datum.getMonth() + 1;
//    var j = datum.getFullYear();
//    if (m < 10) // januari
//    {
//        if (m == 1) {
//            m = '12';
//            j--;
//        }
//        m = String.format('0{0}', m);
//    }
//    var datum = String.format("{0}-{1}-01", j, m, 1);
    var url = String.format("{0}Kilometers?$orderby=EindKm%20desc&$callback=syncFromRemoteKilometersCallback&$format=json",
        query);
    $.ajax({
        dataType: "jsonp",
        jsonpCallback: "syncFromRemoteKilometersCallback",
        url: url
    });
}

function syncFromRemoteKilometersCallback(data) {
    var entities;
    // Find data in results 
    if (data.d[0] == undefined) {
        queryNext = data.d.__next;
        entities = data.d.results;
    }
    else {
        queryNext = "";
        entities = data.d;
    }

    for (var km in entities) {
        syncLocalKm(
            DateDeserialize(entities[km].Datum),
            entities[km].StartKm,
            entities[km].EindKm,
            entities[km].Omschrijving,
            DateDeserialize(entities[km].SynchronisatieMoment),
            entities[km].ID);
    }

    // Continue retrieving results
    if (queryNext > "") {
        syncFromRemoteKilometers();
    }
}

function syncToRemoteKilometers() {
    GetLocalSyncableKilometers(function (row) {
        switch (row.state) {
            case LocalRecordState.Deleted:
                removeRemoteKilometer(row.remoteid, row.id);
                break;
            case LocalRecordState.Updated:
                updateRemoteKilometer(row);
                break;
            case LocalRecordState.New:
                addRemoteKilometer(row);
                break;
            case LocalRecordState.Unchanged:
                checkIfRemotKilometerStillExistInThisForm(row);
                break;
            default:
                /// do nothing
                break;
        }
    });
}

function removeRemoteKilometer(remoteid, id) {
    // Post it
    $.ajax({
        type: RemoteODataAction.Delete,
        contentType: "application/json; charset=utf-8",
        url: String.format("{0}Kilometers({1})", query, remoteid),
        error: function (data) { //Record is al verwijderd uit remote store dus lokaal ook verwijderen. 
            deleteLocalKm(id, null, null);
        }
    });
}

function addRemoteKilometer(row) {
    var synchronisatieMoment = new Date(Date());
    var jsonString = localRecordToRemoteOdataJson(row, synchronisatieMoment);

    // Post it
    $.ajax({
        type: RemoteODataAction.Create,
        contentType: "application/json; charset=utf-8",
        url: String.format("{0}Kilometers", query),
        data: jsonString,
        dataType: "json",
        success: function (result) {
            var km = result["d"];
            setLocalKilometerInSync(row.id, km.ID, synchronisatieMoment);
        },
        error: function (data) { alert("ERROR: " + JSON.stringify(data)) }
    });
}

function updateRemoteKilometer(row) {
    var synchronisatieMoment = new Date(Date());
    var jsonString = localRecordToRemoteOdataJson(row, synchronisatieMoment);

    // Post it
    $.ajax({
        type: RemoteODataAction.Update,
        contentType: "application/json; charset=utf-8",
        url: String.format("{0}Kilometers({1})", query, row.remoteid),
        data: jsonString,
        dataType: "json",
        success: function () {
            setLocalKilometerInSync(row.id, row.remoteid, synchronisatieMoment);
        },
        error: function (data) {
            // record is inmiddels van remote store verwijderd, dus lokaal ook maar verwijderen.
            deleteLocalKm(row.id, null, null);
        }
    });
}

function checkIfRemotKilometerStillExistInThisForm(row) {
    // Post it
    $.ajax({
        dataType: "json",
        type: RemoteODataAction.Read,
        url: String.format("{0}Kilometers?$format=json&$filter=ID%20eq%20{1}", query, row.remoteid),
        success: function (data) {
            if (data.d[0] == undefined) {
                // record is inmiddels van remote store verwijderd, dus lokaal ook maar verwijderen.
                deleteLocalKm(row.id, null, null);
            }
            else {
                // record KAN gewijzigd zijn dus lokaal updaten
                var remoteRow = data.d[0];
                updateLocalKm(
                    row.id,
                    remoteRow.Omschrijving,
                    DateDeserialize(remoteRow.Datum),
                    remoteRow.StartKm,
                    remoteRow.EindKm,
                    LocalRecordState.Unchanged, 
                    null);
            }
        }
    });
}

function localRecordToRemoteOdataJson(row, synchronisatieMoment) {
    var x = {
        ID: row.remoteid,
        Datum: new Date(row.datum),
        StartKm: row.startkm,
        EindKm: row.eindkm,
        Omschrijving: row.omschrijving,
        SynchronisatieMoment: synchronisatieMoment
    };

    var jsonString = JSON.stringify(x);
    return jsonString;
}